class SalesAnalysis {
    constructor() {
        this.charts = {};
        this.filters = {
            timeRange: 'week',
            storeId: 'all'
        };
    }

    init() {
        // 确保DOM元素加载完成后再初始化
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => {
                this.initCharts();
                this.bindEvents();
                this.loadData();
            });
        } else {
            this.initCharts();
            this.bindEvents();
            this.loadData();
        }
    }

    initCharts() {
        try {
            // 销售趋势图
            const salesTrendElement = document.getElementById('salesTrendChart');
            if (salesTrendElement) {
                this.charts.salesTrend = echarts.init(salesTrendElement);
            }

            // 商品销售排行图
            const productRankingElement = document.getElementById('productRankingChart');
            if (productRankingElement) {
                this.charts.productRanking = echarts.init(productRankingElement);
            }

            // 客户消费分析图
            const customerAnalysisElement = document.getElementById('customerAnalysisChart');
            if (customerAnalysisElement) {
                this.charts.customerAnalysis = echarts.init(customerAnalysisElement);
            }

            // 时段销售分布图
            const timeDistributionElement = document.getElementById('timeDistributionChart');
            if (timeDistributionElement) {
                this.charts.timeDistribution = echarts.init(timeDistributionElement);
            }
        } catch (error) {
            console.error('初始化图表失败:', error);
        }
    }

    bindEvents() {
        // 绑定时间范围选择事件
        const timeRangeSelect = document.querySelector('.time-range-select');
        if (timeRangeSelect) {
            timeRangeSelect.addEventListener('change', (e) => {
                this.filters.timeRange = e.target.value;
                this.loadData();
            });
        }

        // 绑定店铺选择事件
        const storeSelect = document.querySelector('.store-select');
        if (storeSelect) {
            storeSelect.addEventListener('change', (e) => {
                this.filters.storeId = e.target.value;
                this.loadData();
            });
        }

        // 绑定导出按钮事件
        const exportButton = document.querySelector('.export-button');
        if (exportButton) {
            exportButton.addEventListener('click', () => {
                this.exportReport();
            });
        }

        // 监听窗口大小变化，重绘图表
        window.addEventListener('resize', () => {
            Object.values(this.charts).forEach(chart => chart.resize());
        });
    }

    async loadData() {
        try {
            // 模拟API调用获取数据
            const response = await this.fetchAnalysisData();
            this.updateCharts(response);
        } catch (error) {
            console.error('加载数据失败:', error);
            // 使用antd的消息提示
            antd.message.error('数据加载失败，请稍后重试');
        }
    }

    async fetchAnalysisData() {
        // 模拟API调用
        return new Promise(resolve => {
            setTimeout(() => {
                resolve({
                    salesTrend: this.getMockSalesTrendData(),
                    productRanking: this.getMockProductRankingData(),
                    customerAnalysis: this.getMockCustomerAnalysisData(),
                    timeDistribution: this.getMockTimeDistributionData()
                });
            }, 1000);
        });
    }

    updateCharts(data) {
        // 更新销售趋势图
        if (this.charts.salesTrend) {
            this.charts.salesTrend.setOption({
                title: { text: '销售趋势分析' },
                tooltip: { trigger: 'axis' },
                xAxis: { type: 'category', data: data.salesTrend.dates },
                yAxis: { type: 'value' },
                series: [{
                    name: '销售额',
                    type: 'line',
                    data: data.salesTrend.values,
                    smooth: true,
                    areaStyle: {}
                }]
            });
        }

        // 更新商品销售排行图
        if (this.charts.productRanking) {
            this.charts.productRanking.setOption({
                title: { text: '商品销售排行' },
                tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
                xAxis: { type: 'value' },
                yAxis: { type: 'category', data: data.productRanking.names },
                series: [{
                    name: '销售量',
                    type: 'bar',
                    data: data.productRanking.values
                }]
            });
        }

        // 更新客户消费分析图
        if (this.charts.customerAnalysis) {
            this.charts.customerAnalysis.setOption({
                title: { text: '客户消费分析' },
                tooltip: { trigger: 'item' },
                series: [{
                    name: '消费层级',
                    type: 'pie',
                    radius: ['50%', '70%'],
                    data: data.customerAnalysis
                }]
            });
        }

        // 更新时段销售分布图
        if (this.charts.timeDistribution) {
            this.charts.timeDistribution.setOption({
                title: { text: '时段销售分布' },
                tooltip: { trigger: 'axis' },
                xAxis: { type: 'category', data: data.timeDistribution.hours },
                yAxis: { type: 'value' },
                series: [{
                    name: '订单量',
                    type: 'bar',
                    data: data.timeDistribution.values
                }]
            });
        }
    }

    getMockSalesTrendData() {
        const dates = Array.from({length: 7}, (_, i) => {
            const date = new Date();
            date.setDate(date.getDate() - i);
            return date.toLocaleDateString();
        }).reverse();
        return {
            dates,
            values: dates.map(() => Math.floor(Math.random() * 10000) + 5000)
        };
    }

    getMockProductRankingData() {
        const products = ['商品A', '商品B', '商品C', '商品D', '商品E'];
        return {
            names: products,
            values: products.map(() => Math.floor(Math.random() * 1000) + 100)
        };
    }

    getMockCustomerAnalysisData() {
        return [
            { value: 1048, name: '高消费' },
            { value: 735, name: '中消费' },
            { value: 580, name: '低消费' }
        ];
    }

    getMockTimeDistributionData() {
        const hours = Array.from({length: 24}, (_, i) => `${i}:00`);
        return {
            hours,
            values: hours.map(() => Math.floor(Math.random() * 100) + 20)
        };
    }

    async exportReport() {
        try {
            // 模拟导出PDF过程
            antd.message.loading('正在生成报表...');
            await new Promise(resolve => setTimeout(resolve, 2000));
            antd.message.success('报表已生成，正在下载...');
        } catch (error) {
            console.error('导出报表失败:', error);
            antd.message.error('导出失败，请稍后重试');
        }
    }
}

export default SalesAnalysis;